//
//  NSObject+SPExchangeMethod.m
//  SPFoundationCategory
//
//  Created by LSP on 2020/9/22.
//  Copyright © 2020 1210233. All rights reserved.
//

#import "NSObject+SPExchangeMethod.h"
#import <objc/runtime.h>

@implementation NSObject (SPExchangeMethod)

+ (void)exchangeMethod:(NSString *)methodName {
    if (!methodName) {
        return;
    }
    [self exchangeMethods:@[methodName]];
}
+ (void)exchangeMethod:(NSString *)methodName withPrefix:(NSString *)prefix {
    [self exchangeMethods:@[methodName] withPrefix:prefix];
}
+ (void)exchangeMethods:(NSArray *)originalSelectors withPrefix:(NSString *)prefix {
    
    for (NSString *selectorName in originalSelectors) {
        SEL originalSelector = NSSelectorFromString(selectorName);
        SEL swizzledSelector = NSSelectorFromString([prefix stringByAppendingString:selectorName]);
        
        Method originalMethod = class_getInstanceMethod(self, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(self,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(self,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
            
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    }
}
+ (void)exchangeMethods:(NSArray *)originalSelectors {
    [self exchangeMethods:originalSelectors withPrefix:@"sp_"];
}

@end
